response.title="Free short Story"
import logging
log=logging.getLogger("CopyPaste")
import random

if not session.categories:
#    session.categories=db.select(db.category.name)
    session.categories=[r.name for r in db().select(db.category.ALL)]


response.menu = [['Love ', True, URL(r=request,f='index',args=['lovestory'])],
['Family', True, URL(r=request,f='index',args=['family'])],['Friend', True, URL(r=request,f='index',args=['friend'])],
['Others', True, URL(r=request,f='index',args=['other'])]]

public_key = '6LcmRboSAAAAAIWImLGqJZAxO5D20tNimm4dTuss'
private_key = '6LcmRboSAAAAAGjbbvOOmLL022i1n2_aHLte8q5I'

def register():
    form=FORM(TABLE(
    TR('alias', INPUT(_name="alias",_type="text")),
    TR('email', INPUT(_name="email",_type="email")),
    TR('password', INPUT(_name="password",_type="text"))),
    RECAPTCHA(request,public_key,private_key),INPUT(_type='submit'))
    if form.accepts(request.vars,session):
        db.person.insert(alias=request.vars.alias,
                            email=request.vars.email,
                            password=request.vars.password)
        session.authorized=form.vars.id
        session.email=form.vars.email
        session.alias=form.vars.alias
        session.flash='user registered'
        redirect(URL(r=request,f='index'))
    return dict(form=form)


	
def login():
    db.person.email.requires=IS_NOT_EMPTY()    
    form=SQLFORM(db.person,fields=['email','password'])
    if FORM.accepts(form,request.vars,session):
       users=db(db.person.email==form.vars.email)\
               (db.person.password==form.vars.password).select()
       if len(users):
          session.authorized=users[0].id
          session.email=users[0].email
          session.alias=users[0].alias
          session.flash='user logged in'
          redirect(URL(r=request,f='index'))
       else:
          form.errors['password']='invdalid password'
    return dict(form=form)

def logout():
	logging.debug('TEST INSIDE WEB@PY')
	logging.info("LOGOUT ")
	session.authorized=None
	session.email=None
	session.alias=None
	session.flash='user logged out'
	redirect(URL(r=request,f='index'))
def info():
    return dict()


def index():
	sorts={'new':~db.story.post_time,
			'comment':~db.story.comments,
			'view':~db.story.clicks}
	try:
		page=int(request.args[2])
		log.warning('page value is got is %s',page)
	except:
		page=0
		log.warning('PAGE IS 0')
	try:
		sort=request.args[1]
		log.warning(' hot value is%',sort)
	except:
		log.warning(' hot value is default')
		sort='comment'
	log.warning('hot value is %s',sort)
	orderby=sorts[sort]
	log.warning('orderby is %s',orderby)
	limitby=(9*page,9*(page+1)+1)
	log.info('after limit by caculation limit is %s',limitby)
	try:
		log.warning('category value is')
		category=request.args[0]
                if category != 'None':
                    log.info('category is %s',category)
                    story=db(db.story.category==category).select(orderby=orderby,limitby=limitby)
                else:
                    story=db().select(db.story.ALL,orderby=orderby,limitby=limitby)
	except:
		category = None
		log.warning('category value is all')
		story=db().select(db.story.ALL,orderby=orderby,limitby=limitby)
	a = len(story)
	log.info('len is %s',a)
	if a != 0:
		feature_number = random.randint(0,a-1)
	else:
		feature_number = 0
	log.info('random number is %s',feature_number)
	return dict(sorttest=sorts,category=category,story=story,sort=sort,sorts=sorts.keys(),page=page,feature_story= feature_number)






def read():
	log.info("******************************************")
	post_id = int(request.args[0])
	post = db(db.story.id == post_id).select()[0]
	post.update_record(clicks=post.clicks+1)
	form = FORM(
		INPUT(_class='hover-star',_type='radio',_name='rating',_value=1,_title='Very poor'),
		INPUT(_class='hover-star',_type='radio',_name='rating',_value=2,_title=' poor'),
		INPUT(_class='hover-star',_type='radio',_name='rating',_value=3,_title='normal'),
		INPUT(_class='hover-star',_type='radio',_name='rating',_value=4,_title='good'),
		INPUT(_class='hover-star',_type='radio',_name='rating',_value=5,_title='Very good'),
		SPAN(_id='hover-test', _style="margin:0 0 0 20px;"),
		DIV(""),
		INPUT(_type='submit', _value="save"),_action=URL(r=request,f='rating',args=[request.args[0]]))
	log.info('test inside web2py %s',request.args[0])
	log.info('***********************************************************************')
	a = comments()
	"""log.info(' comments = %s',a)"""
	if form.accepts(request.vars, session):
		response.flash = 'Thanks for rating'
	elif form.errors:
		response.flash = 'form is invalid'
	return dict(post = post,form=form,a=a)


	
	
	
# Star rating for Story
def rating():
	log.info('RATING FUNCTION')
	log.debug(' request.vars.rating is %s',request.vars.rating)
	log.warning('log warning')
	story=db(db.story.id==request.args[0]).select()[0]
	log.warning(' story[0] is %s', story)
	story.update_record(score= int(request.vars.rating) + story.score, scoringtime=story.scoringtime+1)
	redirect(URL(r=request,f='read',args=[request.args[0]]))
	return dict()
	
def post():
	if not session.authorized:
		redirect(URL(r=request,f='login'))
	form=FORM(TABLE(
	TR('TITLE', INPUT(_name="title",_type="text")),
	TR('Category',SELECT(['family','lovestory','friend','other'],_name="category",_type="text",_requires=IS_IN_SET(['family','lovestory','friend','other']))),
	TR('Writer',INPUT(_name="writer",_type="text")),
	TR('publish_year',INPUT(_name="publish",_type="text")),
	TR('URL',INPUT(_name="url",_type="text")),
	TR('Foreword',INPUT(_name="foreword",_type="text"))),
	TABLE(
	TR(DIV(TEXTAREA(_name="msgpost",_id="msgpost", _cols="50", _rows="10"))),
	TR(INPUT(_type="submit",_value="Save"))))
	if form.accepts(request.vars,session):
            db.story.insert(title=request.vars.title,
					category=request.vars.category,
					writer =request.vars.writer,
					publish= request.vars.publish,
					foreword=request.vars.foreword,
					url=request.vars.url,
					story=request.vars.msgpost,
					author=session.authorized,
					author_alias=session.alias,
					)
            session.flash='story posted'
            redirect(URL(r=request,f='index',args=[form.vars.category]))
	return dict(form=form)
def edit_post():
	if not session.authorized:
		redirect(request.env.http_referer)
	id=request.args[0]
	log.info('id before try is %s',id)
	try:
		story=db(db.story.id==id).select()[0]
		log.info('story id is %s',story)
	except:
		redirect(URL(r=request,f='index'))
		log.info('redirect to index')
	form=FORM(TABLE(
	TR('TITLE', INPUT(_name="title",_type="text",_value=story.title)),
	TR('Category',INPUT(_name="category",_type="text",_value=story.category)),
	TR('URL',INPUT(_name="url",_type="text",_value=story.url)),
	TR('Foreword',INPUT(_name="foreword",_type="text",_value=story.foreword)),
	TR('Writer',INPUT(_name="writer",_type="text",_value=story.writer)),
	TR('Publish',INPUT(_name="publish",_type="text",_value=story.publish))),
	TABLE(
	TR(DIV(TEXTAREA(_name="msgpost",_id="msgpost", _cols="50", _rows="10",_value=XML(story.story)))),
	TR(INPUT(_type="submit",_value="Save"))))
	story.update_record(
					title=request.vars.title,
					category=request.vars.category,
					foreword=request.vars.foreword,
					writer=request.vars.writer,
					publish=request.vars.publish,
					url=request.vars.url,
					story=request.vars.msgpost,
					author=session.authorized,
					author_alias=session.alias,
					)
	log.info('id after try is %s',id)
	if form.accepts(request.vars,session):
		session.flash='comment edited'
		redirect(URL(r=request,f='index'))
	return dict(form=form)


def report():
	try:
		db(db.story.id==request.args[0]).update(flagged=True)
		session.flash='thanks for your feedback'
	except:
		session.flash='internal error'
	redirect(request.env.http_referer)

def delete():
    if not session.authorized: redirect(request.env.http_referer)
    try:
        story=db(db.story.id==request.args[0]).select()[0]
        if story.author==session.authorized:
            db(db.story.id==request.args[0]).delete()
        session.flash='story item deleted'
    except:
        session.flash='internal error'
    redirect(URL(r=request,f='index',args=[story.category]))


def data():
    if not session.m or len(session.m) == 10:
        session.m = []
    if request.vars.q:
        session.m.append(request.vars.q)
    session.m.sort()
    return TABLE(*[TR(v) for v in session.m]).xml()
	
def vote_comment():
	log.info(' Vote_comment')
	id = int(request.vars.q)
	log.info('id is %d',id)
	if not session.authorized: redirect(request.env.http_referer)
	comment=db(db.comment.id==id).select()[0]
	comment.update_record(score=comment.score+1)
	return ""

def report_comment():
    try:
        db(db.comment.id==request.args[0]).update(flagged=True)
        session.flash='thanks for your feedback'
    except:
        session.flash='internal error'
    redirect(request.env.http_referer)

def person():
	session.flash='sorry, not yet implemented'
	redirect(request.env.http_referer)


def comments():
	try: story=int(request.args[0])
	except: redirect(URL(r=request,f='index'))
	if session.authorized:
		item=db(db.story.id==story).select()[0]
		form=FORM(TABLE(
		TR(DIV(TEXTAREA(_name="body",_type="text",_cols="30",_rows="3"))),
		TR(INPUT(_type="submit",_value="Save"))))
		if form.accepts(request.vars,formname='0'): 
			db.comment.insert(author= session.authorized,
							  author_alias=session.alias,
								body = request.vars.body,
								story = item)
			item=db(db.story.id==story).select()[0]
			item.update_record(comments=item.comments + 1)
			response.flash='comment posted'
			
	else: form=None
	try:
		item=db(db.story.id==story).select()[0]
		comments=db(db.comment.story==story).select(orderby=~db.comment.score)
	except: redirect(URL(r=request,f='index'))
	tree={}
	forms={}
	for c in comments:
		if not tree.has_key(c.parente): tree[c.parente]=[c]
		else: tree[c.parente].append(c)
		if session.authorized:
			f=FORM(TABLE(
			TR(DIV(TEXTAREA(_name="body",_type="text",_cols="30",_rows="3"))),
			TR(INPUT(_type="submit",_value="Save"))))
			if f.accepts(request.vars,formname=str(c.id)):
				db.comment.insert(author= session.authorized,
								author_alias=session.alias,
								body = request.vars.body,
								story = item,
								parente = c.id)
				session.flash='comment posted'
				redirect(URL(r=request,args=request.args))
			forms[c.id]=f
	"""log.info('tree is %s',tree)"""
	return dict(item=item,form=form,tree=tree,forms=forms,parent=0,story=story)

def edit_comment():
    if not session.authorized: redirect(request.env.http_referer)
    id=request.args[0]
    try:
        comment=db(db.comment.id==id).select()[0]
        if not comment.author==session.authorized: raise Exception
    except: redirect(URL(r=request,f='index'))
    form=SQLFORM(db.comment,comment,fields=['body'],showid=False,deletable=True,labels={'body':'Comment'})
    if form.accepts(request.vars,session):
        session.flash='comment edited'
        redirect(URL(r=request,f='comments',args=[comment.story]))
    return dict(form=form)

### todo:
"""
prevent users from voting twice: vote, vote_comment
adjust layout
allow different types of story sorting
"""
